let time;
// 订单信息
let data;
// 座位IDs
let seatIds;
// 订单Id
let orderId;
// 判断是否可支付
let payFlag = true;
// 获取订单信息
$(function () {

            // 创建一个Date对象来获取当前时间
var currentDate = new Date();

// 获取当前月份（注意月份从0开始计数，所以要加1）
var currentMonth = currentDate.getMonth() + 1;

// 获取当前日期
var currentDateOfMonth = currentDate.getDate();

// 获取当前小时（24小时制）
var currentHour = currentDate.getHours();

// 获取当前分钟
var currentMinute = currentDate.getMinutes();

// 将获取到的信息拼接成字符串
var currentTime = currentMonth + "月" + currentDateOfMonth + "日 " + currentHour + ":" + currentMinute;

    // 本地存储中获取orderId,座位Id
    let str = localStorage.getItem("orderId");
    orderId = str.split("&")[0];
    seatIds = str.split("&")[1].split(",")
    // 获取座位信息
    let seatArr;
    $.ajax({
        type: 'get',
        url: serverConfig.serverUrl + `/devs/seat/${seatIds}`,
        async: false,//取消异步请求
        success: function (result) {
            if (result.code == 200) {
                seatArr = result.data;
            } else {
                console.log(result)
            }
        }
    })

    // 获取订单信息
    $.ajax({
        type: 'get',
        url: serverConfig.serverUrl + `/devs/order/${orderId}`,
        async: false,//取消异步请求
        success: function (result) {
	    console.log(result)
            data = result.data;
            time = data.createTime;
            djs()
            if (result.code == 200) {
                let str = "";
                str += `<tr class="tr2">
                                <td><<${data.movieTitle}>></td>
                                <td>`+ currentTime +`</td>
                                <td>票无忧线下影院</td>
                                <td>4D厅(儿童需购票)<br>`;
                for (let i = 0; i < seatArr.length; i++) {
                    if (i != seatArr.length - 1) {
                        str += `${seatArr[i].seatRow}排${seatArr[i].seatColumn}座,<br>`
                    } else {
                        str += `${seatArr[i].seatRow}排${seatArr[i].seatColumn}座 <br>`
                    }
                }
                str += `</td></tr>`
                document.getElementById("tbody").innerHTML = str;
                document.getElementById("span3").innerHTML = data.total;
            }
        }
    })

})

let orderData;
$(function () {
    $.ajax({
        url: serverConfig.serverUrl + `/devs/order/${orderId}`,
        type: 'get',
        async: false,
        success: function (result) {
            if (result.code == 200) {
                orderData = result.data;
                time = orderData.createTime;
                payEnd()
                document.getElementById("number").innerText = `项目:  票无忧电影-订单编号:${orderData.number}`
                document.getElementsByClassName("pay-span")[0].innerText = `${orderData.total}`
                document.getElementsByClassName("present-span")[0].innerText = `${orderData.total}`
            } else {
                console.log(result)
            }
        }
    })
})
// 去支付
function toPay() {
    if (payFlag){
        $.ajax({
            type: 'get',
            url: serverConfig.serverUrl + `/devs/alipay/payTicket`,
            data: {userId: orderData.userId, orderNum: orderData.number, price: orderData.total},
            success: function (alipayRedirectHtml) { // 创建一个新的div元素
                var div = document.createElement("div"); // 将后台返回的支付宝支付页面的HTML内容赋值给div的
                div.innerHTML = alipayRedirectHtml; // 获取div中的form元素
                var form = div.querySelector("form"); // 将form添加到文档中
                document.body.appendChild(form); // 提交form表单，实现页面跳转到支付宝支付页面
                form.submit();
            }
        })
    }
    else
        layer.msg('支付超时，请重新选座!', {icon: 2})
}

function djs() {

    let now = new Date();//现在的时间
    let oldTime = now.getTime();//现在时间的毫秒数

    let newTime = (new Date(time)).getTime() + 15 * 60 * 1000

    let minutes = Math.floor((newTime - oldTime) / 1000 / 60)
    let seconds = Math.floor((newTime - oldTime) / 1000 - minutes * 60)

    let jugeTime = (newTime - oldTime);
    if (jugeTime <= 0) {
        payFlag = false;
        clearInterval(ms)
        document.getElementsByClassName("minute")[0].innerText = "00";
        document.getElementsByClassName("second")[0].innerText = "00";
        timeOut();
    } else {
        let str = '0'
        if (minutes < 10)
            minutes = str + minutes

        if (seconds < 10)
            seconds = str + seconds

        document.getElementsByClassName("minute")[0].innerText = `  ${minutes}  `;
        document.getElementsByClassName("second")[0].innerText = `  ${seconds}  `;
    }
}

let ms = setInterval(djs, 1000);


let userInfo;
$(function () {
    $.ajax({
        headers: {
            "token": localStorage.getItem("token")
        },
        type: 'get',
        url: serverConfig.serverUrl + '/devs/user',
        async: false,//取消异步请求
        success: function (result) {
            if (result.code != 200) {
                // layer.msg('您还未登录', {icon: 2})
                localStorage.removeItem('token')
                window.location.href = '../html/login.html';
            } else {
                userInfo = result.data;
            }
        }
    })
})
$(function () {
    let ws;
    //检测浏览器是否支持webSocket
    if ("WebSocket" in window) {
        // $("#message").html("您的浏览器支持webSocket!");
        //模拟产生clientID
        let clientID = userInfo.id;
        //创建 WebSocket 对象,注意请求路径！！！！
        //部署的时候,需要修改成真实的ip地址
        ws = new WebSocket("ws://118.178.105.195:8090/dev/socket/" + userInfo.id);
        //与服务端建立连接时触发
        ws.onopen = function () {
            //模拟发送数据到服务器
            ws.send("你好服务端！我是客户端8090 ");

        }
        //接收到服务端消息时触发
        ws.onmessage = function (evt) {
            let received_msg = evt.data;
            document.getElementById("number").innerText = document.getElementById("number").innerText - (-1)
            layui.use(['layer'], function () {
                var layer = layui.layer;
                // 监听按钮的点击事件
                document.getElementById('message').addEventListener('click', function () {
                    var content = received_msg + "<br>"; // 弹框中显示的内容
                    layer.alert(content);
                });
            });
        };
        //服务端关闭连接时触发
        //服务端关闭连接时触发
        ws.onclose = function () {
            console.error("连接已经关闭.....")
        };
    } else {
        $("#content").html("您的浏览器不支持webSocket！");
    }
})



